﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IngredSubTool
{
    /// <summary>
    /// Interaction logic for SearchResultsView.xaml
    /// </summary>
    public partial class SearchResultsView : UserControl, IAppPage
    {

        public SearchResultsView()
        {
            InitializeComponent();
            Menu.Content = new SideMenu();

            //Show chosen categories if applicable.
            bool usingCategories = false;
            foreach (SearchCategory ctg in DataLoader.SearchCategories)
            {
                if (ctg.Enabled)
                {
                    usingCategories = true;
                    break;
                }
            }

            if (usingCategories)
            {
                ResultsGrid.Margin = new Thickness(250, 125, 100, 70);
                
                foreach (SearchCategory ctg in DataLoader.SearchCategories)
                {
                    if (ctg.Enabled)
                    {
                        CategoryList.Text += (ctg.Name + ", ");
                    }
                }
                CategoryList.Text = CategoryList.Text.Substring(0, CategoryList.Text.Length - 2);
                CategoryList.Visibility = Visibility.Visible;
            }

            //Do search for matching results.
            ObservableCollection<Substitution> matchingSubs = new ObservableCollection<Substitution>();

            foreach (Substitution nextSub in DataLoader.Substitutions)
            {
                Boolean subMatches = true;

                //Check for match with original ingredient that is being replaced.
                if (!nextSub.Original.ToLower().Contains(MainWindow.session.searchTerm.ToLower()))
                    subMatches = false;

                //Ensure substitution matches categories.
                foreach (SearchCategory nextCat in DataLoader.SearchCategories)
                    if (nextCat.Enabled && !nextSub.Categories.ToLower().Contains(nextCat.Name.ToLower()))
                    {
                        subMatches = false;
                        break;
                    }

                // Additional clause so that searching an empty search bar does not bring up the entire substitution list
                if (subMatches && MainWindow.session.searchTerm != "")
                {
                    matchingSubs.Add(nextSub);
                }
            }

            if (matchingSubs.Count == 0)
                TermTitle.Text = "No Results For: " + MainWindow.session.searchTerm;
            else
                TermTitle.Text += MainWindow.session.searchTerm;



            ResultsGrid.ItemsSource = matchingSubs;
            if (MainWindow.session.selectedSub != null)
            {
                ResultsGrid.SelectedItem = MainWindow.session.selectedSub;
                ResultsGrid.ScrollIntoView(MainWindow.session.selectedSub);
                MainWindow.session.selectedSub = null;
            }

        }

        private void Back(object sender, RoutedEventArgs e)
        {
            PageSwitcher.SwitchBack();
        }

        private void RatiosBtn_Click(object sender, RoutedEventArgs e)
        {
            Substitution subtemp = (Substitution)ResultsGrid.CurrentItem;
            MainWindow.session.selectedSub = subtemp;
            PageSwitcher.SwitchForward(new ConversionCalcView());
        }

        private void BookmarkBtn_Click(object sender, RoutedEventArgs e)
        {
            Substitution subObj = (Substitution)ResultsGrid.CurrentItem;
            MainWindow.session.bookmarkSubs.Add(subObj);
            //add function to change color to indicate item is bookmarked
            //add function to remove on second click

        }

        private void CommentSend_Click(object sender, RoutedEventArgs e)
        {
            //Get parent substitution for this comment by climbing the visual tree.
            Button btn = sender as Button;
            var parent = VisualTreeHelper.GetParent(btn);
            while (parent != null && parent.GetType() != typeof(DataGridRow))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            DataGridRow row = parent as DataGridRow;
            Substitution sub = row.Item as Substitution;
            
            //Get entered info.
            StackPanel stack = VisualTreeHelper.GetParent(btn) as StackPanel;
            TextBox userElem = stack.FindName("Username") as TextBox;
            TextBox commElem = stack.FindName("Comment") as TextBox;
            ComboBox ratiElem = stack.FindName("Rating") as ComboBox;

            String username = userElem.Text;
            String comment = commElem.Text;
            int rating = ratiElem.SelectedIndex;

            userElem.Text = "";
            commElem.Text = "";
            ratiElem.SelectedIndex = 0;

            //Create comment.
            Comment newComment = new Comment(sub.Original, sub.Replacement, username, comment, rating, DateTime.Now);

            //Add comment to substitution.
            sub.Comments.Add(newComment);
            sub.UpdateAverage();

            btn.Foreground = Brushes.Red;
            btn.Content = "Comment Sent";

            //Ensure scrollpanel is at bottom.
            parent = VisualTreeHelper.GetParent(btn);
            while (parent != null && parent.GetType() != typeof(ScrollViewer))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            ScrollViewer scroll = parent as ScrollViewer;
            scroll.ScrollToEnd();
        }

        private void Button_LostFocus(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            btn.Foreground = Brushes.Black;
            btn.Content = "Send Comment";
        }
    }
}
